import { Classes } from './../entities/class.entity';
import { Student } from './../entities/student.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';

@Injectable()
export class StudentsService {
  constructor(
    @InjectRepository(Student)
    private readonly studentRepository: Repository<Student>,
    @InjectRepository(Classes)
    private readonly classRepository: Repository<Classes>,
  ) {}

  //根据学号查询名字
  async getSutdentName(id: number) {
    const results = await this.studentRepository.find({
      select: ['name'],
      where: { id: id },
    });
    return results ?? 'not found';
  }

  //新增学生
  async setStudent(id: number, name: string) {
    const results = this.studentRepository
      .createQueryBuilder()
      .insert()
      .into(Student)
      .values([{ id: id, name: name }])
      .execute();
    return results;
  }

  //根据学号查询名字
  async findClass(id: number) {
    const results = await this.classRepository.find({
      where: { id: id },
    });
    return results ?? 'not found';
  }

  //新增给对应id的学生新增课程
  async setClass(studentIds: number[], name: string) {
    const students = await this.studentRepository.findBy({
      id: In(studentIds),
    });
    const results = await this.classRepository.save({
      className: name,
      students: students,
    });
    return results;
  }
}
